<script lang="ts">
	// 服务器后端接口
	import http from '@/api/request.js'
	uni.$http = http
	// 引入 chat SDK 组件
	import { TUIChatKit } from './TUIKit';
	// 引入翻译组件 
	import { locales } from './locales';
	import { TUITranslateService } from '@tencentcloud/chat-uikit-engine';
	// 引入 推送组件
	import TIMPushConfigs from './timpush-configs.json';
	// 引入登录控制
	import { TUILogin } from '@tencentcloud/tui-core';


	// 默认版本为 vue2
	let vueVersion = 2;
	// #ifdef VUE3
	vueVersion = 3;
	// #endif

	TUITranslateService.provideLanguages(locales);
	TUITranslateService.useI18n('zh'); // 不写默认中文

	// 注册 app 推送
	// #ifdef APP-PLUS
	// register TencentCloud-TIMPush  注册腾讯云IM推送
	import { IEnterChatConfig, loginFromStorage, openChat } from './pages/views/loginChat';
	// 加载基础 聊天引擎模块
	import TUIChatEngine from '@tencentcloud/chat-uikit-engine';
	// 加载获取通知模块
	import { getNotificationAuth } from './utils/getNotificationAuth';
	// 获取组件支持
	const TIMPush : any = uni.requireNativePlugin('TencentCloud-TIMPush');
	// 控制台打印推送支持情况 
	console.warn(`TencentCloud-TIMPush: uni.requireNativePlugin ${TIMPush ? 'success' : 'fail'}`);
	uni.$TIMPush = TIMPush;
	uni.$TIMPushConfigs = TIMPushConfigs;
	const enterChatConfig : IEnterChatConfig = {
		isLoginChat: false,
		conversationID: '',
	};
	// register TencentCloud-TUICallKit | 注册腾讯语音通话
	const TUICallKit : any = uni.requireNativePlugin('TencentCloud-TUICallKit');
	console.warn(`TencentCloud-TUICallKit: uni.requireNativePlugin ${TUICallKit ? 'success' : 'fail'}`);
	uni.$TUICallKit = TUICallKit;
	// #endif

	// #ifdef APP-ANDROID
	// 推送消息 铃声 设置
	const notificationChannelInfo = {
		notificationChannelList: [{
			channelID: 'tuikit', // 控制台配置 oppo 的 channelID
			channelName: 'tuikit', // 自定义名称
			channelDesc: '自定义铃音', // 自定义描述
			channelSound: 'private_ring', // 自定义铃音的名称且不需要后缀名
		}],
	};
	uni.$TIMPush.createNotificationChannels(notificationChannelInfo);
	// #endif

	// 组件初始化
	TUIChatKit.init();
	// 参数配置
	const SDKAppID = 20011222; // Your SDKAppID
	const secretKey = 'c2adf5369adda1b686ce91b0e90d9a9d2360fc72c0683d41395d555ec57ae5ec'; // Your secretKey
	uni.$chat_SDKAppID = SDKAppID;
	uni.$chat_secretKey = secretKey;
	uni.$groupid = 'chuangqi';
	uni.$baseUrl = 'https://api.ozgj.top';
	uni.$baseImgUrl = 'https://api.ozgj.top';

	import { genTestUserSig } from './TUIKit/debug';
	import { loginChat } from './pages/views/loginChat';



	export default {

		onLaunch: function () {
			// 默认提示
			console.log('App Launch')

			// 调用当前群组配置
			this.getGroupConfig();

			// 通话记录获取
			if (uni.getSystemInfoSync().platform === 'android') {
				// 调用插件
				uni.authorize({
					scope: 'android.permission.READ_CALL_LOG',
					success() {
						uni.requireNativePlugin('calllogplugin').getCallLogs({
							success(res) {
								console.log('通话记录', res);
							},
							fail(err) {
								console.error('获取失败', err);
							}
						});
					},
					fail() {
						uni.showToast({ title: '请开启通话记录权限', icon: 'none' });
					}
				});
			}

			// 方式2： 登录函数登录
			// #ifdef APP-PLUS
			// 在 App.vue, 生命钩子 onLaunch 中监听
			if (typeof uni.$TIMPush === 'undefined') {
				console.warn('如果您使用推送功能，需集成 TIMPush 插件，使用真机运行并且自定义基座调试，请参考官网文档：https://cloud.tencent.com/document/product/269/103522');
			} else {
				getNotificationAuth();
				uni.$on('uikitLogin', () => {
					enterChatConfig.isLoginChat = true;
					openChat(enterChatConfig);
				});
				uni.$TIMPush.setOfflinePushListener((data) => {
					const { notification = '' } = data?.data || {};
					if (!notification) {
						return;
					}
					const { entity } = JSON.parse(notification);
					const type = entity.chatType === 1 ? TUIChatEngine.TYPES.CONV_C2C : TUIChatEngine.TYPES.CONV_GROUP;
					enterChatConfig.conversationID = `${type}${entity.sender}`;
					if (enterChatConfig.isLoginChat && entity.sender) {
						openChat(enterChatConfig);
					}
				});
				loginFromStorage();
			}
			// #endif

			// 其他业务处理
			// 获取系统信息 自动适配
			uni.getSystemInfo({
				success: function (res) {
					uni.setStorageSync('windowWidth', res.windowWidth)
					uni.setStorageSync('iframeHeight', parseInt(res.windowWidth * 0.6))
				}
			});

			// 如果是登录状态 | sdk 登录状态OK
			if (uni.getStorageSync('userTencentID')) {
				let userID = uni.getStorageSync('userTencentID')
				const options = genTestUserSig({
					SDKAppID: uni.$chat_SDKAppID,
					secretKey: uni.$chat_secretKey,
					userID: userID,
				});
				const loginInfo = {
					SDKAppID: uni.$chat_SDKAppID,
					userID: userID,
					userSig: options.userSig,
					useUploadPlugin: true,
					framework: `vue2`,
					TIMPush: uni.$TIMPush, // register TencentCloud-TIMPush
					pushConfig: {
						androidConfig: uni.$TIMPushConfigs, // Android timpush-configs.json
						iOSConfig: {
							iOSBusinessID: '', // iOS Certificate ID
						},
					},
				};
				loginChat(loginInfo).catch(() => {
					uni.showToast({
						title: TUITranslateService.t('Login.登录失败'),
						icon: 'none',
					});
				});
			}
		},
		onShow: function () { },
		onHide: function () { },
		methods: {
			async getGroupConfig() {
				// 模拟正则表达式获取 | 后面的默认的 正则表达式 里面的
				let groupID = uni.$groupid
				await uni.$http('/home/index/get_group_cfg', 'post', { groupid: groupID }).then((res) => {
					if (res.data.code == 200) {
						// 存入全部
						uni.setStorageSync('group_cfg', JSON.stringify(res.data.data))
						// 单独存入客服
						uni.setStorageSync('kefu_url', res.data.data.cfg_kefu_url)
						// 单独存入 正则表达式
						uni.setStorageSync('regTest', res.data.data.cfg_filter_system_rule)
						// 单独存入 发现地址
						uni.setStorageSync('web_url', res.data.data.cfg_weburl)
					} else {
						uni.showToast({
							title: "失败原因:" + res.data.msg,
							icon: 'none',
							time: 2000
						})
					}
				})
			}
		}
	};
</script>
<style lang="scss">
	@import "uview-plus/index.scss";

	/* common css for page */
	uni-page-body,
	html,
	body,
	page {
		width: 100% !important;
		height: 100% !important;
		overflow: hidden;
	}

	/* ✅ PC端H5时，固定居中小屏 */
	@media screen and (min-width: 768px) {
		body {
			background-color: transparent;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100vh;
		}

		#app {
			width: 410px !important;
			height: 894px !important; /* 844px + 50px给tabBar */
			margin: auto;
			border-radius: 20px;
			overflow: hidden;
			box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
			background: #fff;
			position: relative !important;
		}

		uni-page-body,
		page {
			width: 410px !important;
			height: 900px !important;
			position: relative !important;
		}

		/* ✅ 修复顶部导航栏 */
		.uni-page-head {
			width: 410px !important;
			position: fixed !important;
			top: 50% !important;
			left: 50% !important;
			transform: translate(-50%, -50%) translateY(-447px) !important;
			border-radius: 20px 20px 0 0 !important;
			overflow: hidden;
			z-index: 1000;
			background: #f8f8f8 !important;
			border-bottom: none !important;
			box-shadow: none !important;
		}

		/* ✅ 修复底部tabBar - 关键修改 */
		.uni-tabbar {
			width: 410px !important;
			position: fixed !important;
			bottom: 52% !important;
			left: 50% !important;
			transform: translate(-50%, 50%) translateY(447px) !important;
			border-radius: 0 0 20px 20px !important;
			overflow: hidden;
			z-index: 1000;
			background: #fff !important;
			border-top: none !important;
			box-shadow: none !important;
		}

		/* ✅ 修复内容区域 */
		.uni-page-head ~ .uni-page-body {
			position: absolute !important;
			top: 44px !important;
			bottom: 50px !important;
			left: 0 !important;
			width: 100% !important;
			height: auto !important;
			border-radius: 0 !important;
			background: #fff !important;
			border: none !important;
		}
	}
</style>